<template>
  <div>
    <button @click="startRecording" :disabled="recording">开始录音</button>
    <button ref="buttonRef" @click="stopRecording" :disabled="!recording">停止录音</button>
    <audio ref="audioRef" controls></audio>
  </div>
</template>

<script>
import { ref } from 'vue'

export default {
  name: 'audioView',
  setup() {
    const recording = ref(false)
    const mediaStream = ref(null)
    const mediaRecorder = ref(null)
    const audioChunks = ref()
    const audioRef = ref(null)

    const startRecording = async () => {
      try {
        // 获取用户麦克风权限
        mediaStream.value = await navigator.mediaDevices.getUserMedia({
          audio: true
        })
        // 创建一个 MediaRecorder 实例
        mediaRecorder.value = new MediaRecorder(mediaStream.value)
        audioChunks.value = []

        // 当录音数据可用时触发事件
        mediaRecorder.value.ondataavailable = (event) => {
          if (event.data.size > 0) {
            audioChunks.value.push(event.data)
            playAudio()
          }
        }
        /** 开始录音 */
        mediaRecorder.value.start()
        recording.value = true
      } catch (error) {
        console.error('获取麦克风权限失败:', error)
      }
    }

    const stopRecording = () => {
      if (mediaRecorder.value) {
        // 停止录音
        mediaRecorder.value.stop()
        // 停止麦克风访问
        mediaStream.value.getTracks().forEach((track) => track.stop())
        recording.value = false
      }
    }

    const audioData = ref(null)

    /** 上传录音文件 */
    const uploadRecording = async (audioData) => {
      const formData = new FormData()
      formData.append('audio', audioData)
      try {
        // 使用 Axios 发送录音文件到后端
        // const response = await xxx("YOUR_BACKEND_API_URL", formData);
        // console.log("文件上传成功:", response.data);
      } catch (error) {
        console.error('文件上传失败:', error)
      }
    }

    // 录音文件流转换
    const playAudio = () => {
      // 创建 Blob 对象并生成音频文件的 URL
      const audioBlob = new Blob(audioChunks.value, {
        type: 'audio/webm'
      })

      /** 播放录音文件 */
      audioRef.value.src = URL.createObjectURL(audioBlob)
      uploadRecording(audioBlob)
    }

    return {
      audioData,
      uploadRecording,
      audioRef,
      recording,
      startRecording,
      stopRecording
    }
  }
}
</script>

<style></style>
